package hip.util;

import org.junit.Test;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StreamTest {

    private List<String> stringList() throws IOException {
        URL resource = StreamTest.class.getResource("/employee.txt");
        File file = new File(resource.getPath());

        BufferedReader bufferedReader = null;

        bufferedReader = new BufferedReader(new FileReader(file));

        String str = null;
        List<String> list = new ArrayList<>();
        while ((str = bufferedReader.readLine()) != null) {
            System.out.println(str);
            list.add(str);
        }
        return list;
    }

    /**
     * stream.map()
     */
    @Test
    public void test1() {
        try {

            List<String> list = stringList();
            List<Employee> employeeList = list.stream().map(word -> {
                List<String> words = Arrays.stream(word.split(",")).collect(Collectors.toList());
                return new Employee(words.get(0), Integer.parseInt(words.get(1)), words.get(2), words.get(3));
            }).collect(Collectors.toList());

            employeeList.forEach(System.out::println);

            Map<String, Long> collect = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));

            System.out.println(collect);

            int sum = employeeList.stream().mapToInt(Employee::getAge).sum();
            System.out.println(sum);

            int reduce = employeeList.stream().mapToInt(Employee::getAge).reduce(0, Integer::sum);

            System.out.println("reduce = " + reduce);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * stream().flatMap
     */
    @Test
    public void test2() {
        try {

            List<String> list = stringList();
            List<Object> collect = list.stream().flatMap(word -> {
                List<String> words = Arrays.stream(word.split(",")).collect(Collectors.toList());


                List<Employee> employees = new ArrayList<>();
                Employee employee = new Employee(words.get(0), Integer.parseInt(words.get(1)), words.get(2), words.get(3));
                employees.add(employee);
                Employee employee2 = new Employee(words.get(0), Integer.parseInt(words.get(1)), words.get(2), words.get(3));
                employees.add(employee2);
                return employees.stream();

            }).collect(Collectors.toList());

            collect.forEach(System.out::println);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * stream groupBy
     */
    @Test
    public void test3() {

    }
}
